import OSS from "ali-oss";
import Axios from "axios";

export async function upLoadFile({ files }, getFileUrl) {
  let resData = await clientConfig();
  if (resData.code === "0") {
    resData = resData.data;
    const client = getClient(resData.sts);
    let fileUrl = resData.accessUrl;
    if (files.length !== 0) {
      uploadReader(files[0], resData, client, fileUrl, getFileUrl);
    }
  }
}
// 实例化FileReader
function uploadReader(file, resData, client, fileUrl, getFileUrl) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = async function() {
    const { ossfile, key, headers } = getOssParams.apply(this, [
      file.name,
      resData,
    ]);
    const res = await client.multipartUpload(key, ossfile, {
      headers: headers,
    });
    const url = fileUrl + res.name;
    getFileUrl(url);
  };
}
// 访问公司的接口获取配置
async function clientConfig() {
  var url =
    "https://mhp-copdtest.boe.com.cn/console/home/file/upload?sys=mhealth&source=img";
  return Axios.get(url).then(function(res) {
    return res.data.data;
  });
}
// 实例化OSS
function getClient(creds) {
  return new OSS({
    region: creds.region,
    secure: true,
    accessKeyId: creds.accessKeyId,
    accessKeySecret: creds.accessKeySecret,
    stsToken: creds.securityToken,
    bucket: creds.bucket,
  });
}
// 获取oss参数
function getOssParams(name, resData) {
  const suffix = name.substring(name.lastIndexOf("."));
  const filename = resData.path + "/" + resData.filename;
  const key = filename + suffix;
  const headers = {
    "Content-Type": "image/jpeg",
    "Content-Disposition": "inline;filename=" + filename,
  };
  const dataurl = this.result;
  const arr = dataurl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const ossfile = new File([u8arr], name, {
    type: mime,
  });

  return { ossfile, key, headers };
}
